package cn.com.infohold.smartcity.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.WindowManager;
import android.widget.PopupWindow;

import java.lang.ref.WeakReference;

/**
 * Created by Mr.Fan on 2016-6-14.
 */
public class RunningDialog {
    private static WeakReference<Object> reference = null;
    protected static final float dimAmount = 0.3f;

    protected static void instantiateDialog(Object dialog) {
        dismiss();
        RunningDialog.reference = new WeakReference<>(dialog);
    }

    public static void dismiss() {
        Object obj = reference == null ? null : reference.get();
        if (obj instanceof Dialog) {
            Dialog d = (Dialog) obj;
            if (d.isShowing())
                d.dismiss();
        } else if (obj instanceof PopupWindow) {
            PopupWindow p = (PopupWindow) obj;
            if (p.isShowing())
                p.dismiss();
        }
    }

    protected static Object getDialog() {
        return reference != null ? reference.get() : null;
    }

    public static void onStop() {
        dismiss();
    }


    protected static void setActivityDim(Context context) {
        setActivityDim(context, dimAmount);
    }

    protected static void setActivityDim(Context context, float dimAmount) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            lp.alpha = 1 - dimAmount; //0.0-1.0
            activity.getWindow().setAttributes(lp);
        }
    }

    protected static class PopupWindowDismissCallback implements PopupWindow.OnDismissListener {
        private WeakReference<Context> reference;

        public PopupWindowDismissCallback(Context context) {
            this.reference = new WeakReference<>(context);
        }

        @Override
        public void onDismiss() {
            if (reference != null) {
                setActivityDim(reference.get(), 0.0f);
            }
        }
    }

}
